import ccxt
import time
from datetime import datetime

# zhanggang
# api_key = 'JCtIkLqLQAyCw6pCO6YoqmFMIQ6IeQFKqXjLqh0OctKTh5tb6AzvtTJvqDN4iZc2'
# api_secret = 'YiV0bJt1z0epEED6pA8MgkLAslxNPB6xuqZFyc01VL0dbJ9vBBuLx73C6ZsL4hL9'

# # liujiahuang
# api_key = "ZDloEnO2ubVlWoAXG7tW1a2TFBViMUDRI3GJzrLHi1vczTefoHnn8Ivlh4rMRI11"
# api_secret = "ozT9YH60jGdmEkSudLVdxKZxnKsiC3knMOOes5k2XBb0cd946qw48WK4kfxCGNan"

api_key = "bOWuVDgNOF4nzUnRDkAqwHHotZfIeTCEp7Ml8c19usWtVSDYboDu3z2QYwwPJtFJ"
api_secret = "kqFeEFS3ZPmiiAu68aBzsUcHNJMJK9uBD86NFg8L21lQwVvIGUPz70yGQj0qVfHn"

# 初始化Binance交易所
binance = ccxt.binance({
    'apiKey': api_key,
    'secret': api_secret,
})

balance = binance.fetch_balance()

# 获取所有市场对
markets = binance.load_markets()

# 需要忽略的币种
ignore_assets = ['ETH', 'BTC', 'BNB', 'USDT']

# 遍历账户中所有资产
for asset, details in balance['total'].items():
    if asset in ignore_assets or details <= 0:
        continue

    # 检查 asset/USDT 或 USDT/asset 是否存在
    symbol = None
    order_type = None
    if f'{asset}/USDT' in markets:
        symbol = f'{asset}/USDT'
        order_type = 'sell'
    elif f'USDT/{asset}' in markets:
        symbol = f'USDT/{asset}'
        order_type = 'buy'
    
    if symbol is None:
        print(f"No USDT market found for {asset}, skipping.")
        continue

    try:
        # 获取当前市场价格
        ticker = binance.fetch_ticker(symbol)
        price = ticker['last']

        if order_type == 'sell':
            # 卖出该资产以兑换USDT
            print(f"Selling {asset} to USDT via {symbol}")
            amount_to_sell = balance['free'][asset]
            order = binance.create_market_sell_order(symbol, amount_to_sell)
        elif order_type == 'buy':
            # 用USDT买入资产，然后换成USDT
            print(f"Buying USDT with {asset} via {symbol}")
            usdt_balance = balance['free']['USDT']
            amount_to_buy = usdt_balance / price  # 用USDT买资产
            order = binance.create_market_buy_order(symbol, amount_to_buy)
        
        print(order)
    except Exception as e:
        print(f"Could not trade {asset} to USDT: {str(e)}")